﻿using Api.Shared.MyPlc.S7;
using Api.Shared.Sugar;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Net.Http;

namespace KxApp
{
    public class StartupInitializationService : IHostedLifecycleService
    {
        private readonly ILogger<StartupInitializationService> logger;
        private readonly ISugarClientService helper;
        private readonly IHttpClientFactory clientFactory;
        private readonly IS7ConnService s7;
        private ConfigurationBuilder cfgBuilder = new ConfigurationBuilder();
        private IConfigurationRoot configRoot;
        private string ip = string.Empty;

        public StartupInitializationService(ILogger<StartupInitializationService> logger, [FromKeyedServices(nameof(SqlName.sqliteST))] ISugarClientService helper, IHttpClientFactory clientFactory, IS7ConnService s7)
        {
            this.logger = logger;
            this.helper = helper;
            this.clientFactory = clientFactory;
            this.s7 = s7;
            cfgBuilder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
            configRoot = cfgBuilder.Build();
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        public async Task StartedAsync(CancellationToken cancellationToken)
        {
            s7.ConnPlc(configRoot["PlcIp"]?? "192.168.5.11");
            ////GET
            //BaseRequest request = new BaseRequest();
            //request.MethodSharp = Method.GET;
            //request.Route = $"api/private/v1/Plc/Test3";
            //string webUrl = @"http://localhost:8889/";
            //ApiResponse<ApiData>? res = new();
            //HttpRestClient myClient = new(webUrl);
            //res = await myClient.ExecuteAsync<ApiData>(request);


            ////POST
            //BaseRequest request = new BaseRequest();
            //request.MethodSharp = Method.POST;
            //request.Route = $"api/private/v1/Plc/MyClientTest";
            //string webUrl = @"http://localhost:8889/";
            //ApiResponse<Person>? res = new();
            //HttpRestClient myClient = new(webUrl);
            //Person person = new()
            //{
            //    Age = 96,
            //    Name = "叮咚鸡"
            //};
            //request.Parameter = person;
            //res = await myClient.ExecuteAsync<Person>(request);

            ////PoST2
            //using HttpClient? client = clientFactory.CreateClient();
            //client.Timeout = TimeSpan.FromSeconds(20);

            //var baseRequest = new BaseRequest
            //{
            //    Method = HttpMethod.Post,
            //    Route = "/api/private/v1/Plc/MyClientTest",
            //    Parameter = new Person { Age = 19, Name = "xiaoM" }
            //};
            ////MyHttpClient myHttpClient = new(ip, client);
            //MyHttpClient myHttpClient = new(client, "myIp");
            //var response = await myHttpClient.ExecuteAsync<Person>(baseRequest);
            //JsonSerializerOptions options = new()
            //{
            //    WriteIndented = true,
            //    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            //};
            //var str = JsonSerializer.Serialize(response, options);

            //Task.Run(async () =>
            //{
            //    while (true)
            //    {
            //        logger.LogWarning($"输出日志:{DateTime.Now}");
            //        await Task.Delay(1000);
            //    }
            //});

            //string str1 = configRoot["PlcIp"];

            //logger.LogError($"Ip为{str1}");

            //helper.Db.CodeFirst.SetStringDefaultLength(500).InitTables(typeof(Person));

            //List<Person> ps = new();
            //for (int i = 0; i < 100; i++)
            //{
            //    Person p = new()
            //    {
            //        Age = i,
            //        Name = $"名字{i}"
            //    };
            //    ps.Add(p);
            //}
            //var res = await helper.Db.Insertable(ps).ExecuteCommandAsync();
            //return Task.CompletedTask;


        }

        public Task StartingAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        public Task StoppedAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        public Task StoppingAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }
}